package com.telenav.snowsweeper.renderer;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;

import com.telenav.snowsweeper.R;
import com.telenav.snowsweeper.data.Point;
import com.telenav.snowsweeper.data.PointsManager;
import com.telenav.snowsweeper.framework.ui.IObjectRenderer;
import com.telenav.snowsweeper.util.ResourceUtil;

public class VehicleRenderer implements IObjectRenderer {

	private Paint paint = new Paint();
	private RendererParams params = new RendererParams();
	
	@Override
	public void render(Canvas canvas, Layer layer) {
		if (layer == Layer.CAR) {
			int[] xy = params.screenXY; 
			if (xy != null) {
				Bitmap car = ResourceUtil.loadImage(R.drawable.car);
				Matrix m = new Matrix();
				m.postTranslate(xy[0] - (car.getWidth() >> 1), xy[1] - (car.getHeight() >> 1));
				m.postRotate(params.heading, xy[0], xy[1]);
				canvas.drawBitmap(car, m, paint);
			}
		}
	}

	@Override
	public void build(long timeStamp) {
		params.dirty = true;
		if (params.dirty) {
			synchronized (params) {
				if (params.dirty) {
					params.screenXY = params.location.getScreenXY(timeStamp);
					params.dirty = false;
				}
			}
		}
	}
	
	public RendererParams getRendererPamars() {
		return params;
	}
	
	public class RendererParams {
		Point location;
		
		private RendererParams() {
			location = PointsManager.getPoint(0, 0);
		}
		
		int heading;
		int[] screenXY;
		boolean dirty;
		
		public synchronized void go2Location(Point p) {
			location = p;
			heading = 270;
			dirty = true;
		}
		
		public synchronized Point go2Up() {
			location = PointsManager.getTopPointIfHave(location);
			heading = 270;
			dirty = true;
			return location;
		}

		public synchronized Point go2Down() {
			location = PointsManager.getBottomPointIfHave(location);
			heading = 90;
			dirty = true;
			return location;
		}

		public synchronized Point go2Left() {
			location = PointsManager.getLeftPointIfHave(location);
			heading = 180;
			dirty = true;
			return location;
		}

		public synchronized Point go2Right() {
			location = PointsManager.getRightPointIfHave(location);
			heading = 0;
			dirty = true;
			return location;
		}
		
		public Point getLocation() {
			return location;
		}
	}
}
